<template>
  <div class="edit-profile">
    <h2>编辑个人信息</h2>
    <form @submit.prevent="handleSubmit">
      <!-- 昵称 -->
      <div class="form-item">
        <label>昵称：</label>
        <input v-model="form.name" type="text" />
      </div>

      <!-- 个性签名 -->
      <div class="form-item">
        <label>个性签名：</label>
        <textarea v-model="form.signature" rows="3" />
      </div>

      <!-- 性别 -->
      <div class="form-item">
        <label>性别：</label>
        <el-radio-group v-model="form.sex">
          <el-radio label="1">男</el-radio>
          <el-radio label="2">女</el-radio>
        </el-radio-group>
      </div>

      <!-- 上传头像 -->
      <div class="form-item">
        <label>头像：</label>
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="true"
          :http-request="uploadAvatar"
        >
          <img v-if="form.avatar" :src="form.avatar" class="avatar-preview" />
          <div v-else class="avatar-placeholder">点击上传</div>
        </el-upload>
      </div>

      <!-- 保存按钮 -->
      <div class="btn-group">
        <el-button type="primary" native-type="submit">保存资料</el-button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserInfo, updateUserInfo } from '@/apis/user'
import { uploadAvatarFile } from '@/apis/file'
const router = useRouter()

const form = reactive({
  name: '',
  signature: '',
  sex: '1',
  avatar: '', // 图片地址 URL
})

// 获取用户信息
const fetchUserInfo = async () => {
  const uid = localStorage.getItem('uid')
  if (!uid) {
    ElMessage.error('用户未登录')
    router.push('/login')
    return
  }

  try {
    const res = await getUserInfo(uid)
    if (res.code === '200') {
      const data = res.data
      form.name = data.username
      form.signature = data.signature || ''
      form.sex = data.sex?.toString() || '1'
      form.avatar = data.avatar || ''
    }
  } catch {
    ElMessage.error('获取用户信息失败')
  }
}

onMounted(fetchUserInfo)

// 上传头像（自动触发）
const uploadAvatar = async ({ file }) => {
  const uid = localStorage.getItem('uid')
  const formData = new FormData()
  formData.append('file', file)
  formData.append('uid', uid)

  try {
    const res = await uploadAvatarFile(formData)
    if (res.code === '200') {
      form.avatar = res.data // 拿到图片 URL
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error(res.message || '上传失败')
    }
  } catch {
    ElMessage.error('上传出错，请稍后再试')
  }
}

// 保存资料
const handleSubmit = async () => {
  const uid = localStorage.getItem('uid')
  const payload = {
    uid,
    username: form.name,
    signature: form.signature,
    sex: form.sex,
    avatar: form.avatar,
  }

  try {
    const res = await updateUserInfo(payload)
    if (res.code === '200') {
      ElMessage.success('资料已保存')
      router.push(`/home/user/${uid}`)
    } else {
      ElMessage.error(res.message || '保存失败')
    }
  } catch {
    ElMessage.error('保存失败，请稍后再试')
  }
}
</script>

<style scoped>
.edit-profile {
  max-width: 600px;
  margin: 0 auto;
  background: white;
  padding: 24px;
  border-radius: 10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
h2 {
  margin-bottom: 20px;
  text-align: center;
}
.form-item {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
}
label {
  font-weight: bold;
  margin-bottom: 6px;
}
input,
textarea {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}
.avatar-uploader {
  border: 1px dashed #ccc;
  border-radius: 6px;
  text-align: center;
  padding: 10px;
  cursor: pointer;
  width: 160px;
}
.avatar-preview {
  width: 100%;
  height: auto;
  max-height: 160px;
  border-radius: 6px;
  object-fit: cover;
}
.avatar-placeholder {
  color: #999;
  font-size: 14px;
}
.btn-group {
  text-align: center;
  margin-top: 20px;
}
</style>
